package com.xx.springboot.aspect;

import com.xx.springboot.annotation.Log;
import com.xx.springboot.entity.Syslog;
import com.xx.springboot.entity.User;
import com.xx.springboot.service.ISyslogService;
import com.xx.springboot.utils.IpUtils;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;


@Aspect
@Component
public class LogAspect {

    @Autowired
    private ISyslogService syslogService;

    @Pointcut("@annotation(com.xx.springboot.annotation.Log)")
    public void pointcut() { }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) {
        long beginTime = System.currentTimeMillis();
        // 执行方法
        try {

            Object res = point.proceed();
            // 执行时常
            long time = System.currentTimeMillis() - beginTime;

            // 保存日志
            saveLog(point, time);
            return res;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return null;
    }


    /**
     * <p>
     *      TODO:将访问信息, 存入到数据库中
     * </p>
     * @Author hcg
     * @Date 2018-11-15 10:07
     * @Param time -> 处理时间
     * @return
     **/
    private void saveLog(ProceedingJoinPoint point, long time) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        Syslog syslog = new Syslog();
        Log logAnnotation = method.getAnnotation(Log.class);
        if (logAnnotation != null) {
            // 注解上面的描述
            syslog.setOperation(logAnnotation.value());
        }
        // 请求的方法名
        String className = point.getTarget().getClass().getName();
        String methodName = signature.getName();
        syslog.setMethod(className + "." + methodName + "()");

        // 请求方法的参数值
        Object[] args = point.getArgs();

        // 请求的方法的参数值
        LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
        String[] paramNames = u.getParameterNames(method);
        if (args != null && paramNames != null) {
            String params = "";
            for (int i = 0; i < args.length; i++) {
                params += "  " + paramNames[i] + ": " + args[i];
            }
            syslog.setParams(params);
        }

        // 设置IP地址
        syslog.setIp(IpUtils.getIpAddr());

        syslog.setUsername(getUserName());
        syslog.setTime((int) time);
        syslog.setCreateTime(LocalDateTime.now());

        // 保存系统日志
        syslogService.save(syslog);
    }


    /**
     * <p>
     *      TODO:获取得到当前用户名
     * </p>
     * @Author hcg
     * @Date 2018-11-15 10:07
     **/
    private String getUserName() {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        // 模拟一个用户名
        if (user == null) {
            return "guest";
        } else {
            return user.getUsername();
        }
    }
}
